from django.shortcuts import render, redirect, reverse
from django.db.models import Q
from django import forms
from django.http import JsonResponse

from web.utils.pager import Pagernation
from web import models
from web.utils.bootstrap import BootstrapForm
from web.utils.link import filter_reverse
from web.utils.response import BaseResponse

def device_type_list(request):
    keyword = request.GET.get('keyword', "").strip()
    conn = Q()
    if keyword:
        conn.connector = "OR"
        conn.children.append('title__contains', keyword)

    queryset = models.DeviceType.objects.filter(conn)

    pager = Pagernation(request, queryset)

    context = {
        'pager': pager,
        'keyword': keyword
    }
    return render(request, 'device_type_list.html', context)


class DeviceTypeModelForm(BootstrapForm, forms.ModelForm):
    class Meta:
        model = models.DeviceType
        fields = "__all__"


def device_type_add(request):
    if request.method == "GET":
        form = DeviceTypeModelForm()
        return render(request, 'form.html', {'form': form})
    form = DeviceTypeModelForm(data=request.POST)
    if not form.is_valid():
        return render(request, 'form.html', {'form': form})
    form.save()

    return redirect(reverse('device_type_list'))


def device_type_edit(request, pk):
    obj = models.DeviceType.objects.filter(id=pk).first()
    if request.method == "GET":
        form = DeviceTypeModelForm(instance=obj)
        return render(request, 'form.html', {'form': form})
    form = DeviceTypeModelForm(data=request.POST, instance=obj)
    if not form.is_valid():
        return render(request, 'form.html', {'form': form})
    form.save()
    return redirect(filter_reverse(request, '/device_type/list/'))


def device_type_delete(request):
    cid = request.GET.get('cid', 0)
    if not cid:
        res = BaseResponse(status=False, detail='请选择要删除的数据')
        return JsonResponse(res.dict)

    exists = models.DeviceType.objects.filter(id=cid).exists()
    if not exists:
        res = BaseResponse(status=False, detail="要删除的数据不存在")
        return JsonResponse(res.dict)
    models.DeviceType.objects.filter(id=cid).delete()
    res = BaseResponse(status=True)
    return JsonResponse(res.dict)

